package com.agriculture.controller;

import com.agriculture.common.Result;
import com.agriculture.service.BlockchainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/api/blockchain")
public class BlockchainTestController {

    @Autowired
    private BlockchainService blockchainService;

    @PostMapping("/create")
    public Result<?> testCreateProduct(@RequestBody Map<String, Object> productInfo) {
        try {
            String result = blockchainService.testCreateProduct(productInfo);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("测试创建产品失败: " + e.getMessage());
        }
    }

    @PostMapping("/update")
    public Result<?> testUpdateProductInfo(@RequestBody Map<String, String> params) {
        try {
            String result = blockchainService.testUpdateProductInfo(
                params.get("productAddress"), 
                params.get("newInfo")
            );
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("测试更新产品信息失败: " + e.getMessage());
        }
    }

    @GetMapping("/info")
    public Result<?> testGetProductInfo(@RequestParam String productAddress) {
        try {
            String result = blockchainService.testGetProductInfo(productAddress);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("测试获取产品信息失败: " + e.getMessage());
        }
    }

    @GetMapping("/status")
    public Result<?> testGetChainStatus() {
        try {
            String result = blockchainService.testGetChainStatus();
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("测试获取链状态失败: " + e.getMessage());
        }
    }

    @PostMapping("/contract/call")
    public Result<?> testCallContract(
            @RequestParam String contractAddress,
            @RequestParam String funcName,
            @RequestBody(required = false) Map<String, String> funcParams) {
        try {
            String response = blockchainService.testCallContract(contractAddress, funcName, funcParams);
            return Result.success(response);
        } catch (Exception e) {
            return Result.error("测试调用合约失败: " + e.getMessage());
        }
    }
} 